package cn.itsource.user.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.Md5Utils;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.mapper.LogininfoMapper;
import cn.itsource.user.mapper.UserMapper;
import cn.itsource.user.service.IUserService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void add(User user) {
        //生成盐值，再加密加盐
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        //添加logininfo
        Logininfo logininfo = new Logininfo();
        //根据两张表相同的字段匹配，然后复制到另一张表中
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1); //设置为用户
        logininfo.setDisable(true); //启用
        //添加到数据库 - 添加后才会有自增id
        logininfoMapper.add(logininfo);
        //设置user表的Logininfo_id字段
        user.setLogininfoId(logininfo.getId());
        super.add(user);
    }

    @Override
    public void update(User user) {
        //生成盐值，再加密加盐
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        //获取到之前的数据 - 有一些数据前端没有修改，我们获取出来后重新添加进去
        User dbUser = userMapper.findOne(user.getId());
        user.setLogininfoId(dbUser.getLogininfoId());
        user.setCreatetime(dbUser.getCreatetime());
        user.setAge(dbUser.getAge());
        super.update(user);
        //根据logininfo_id获取到数据库中的logininfoer
        Logininfo logininfo = logininfoMapper.findOne(user.getLogininfoId());
        //同步修改logininfo中的字段
        logininfo.setUsername(user.getUsername());
        logininfo.setPhone(user.getPhone());
        logininfo.setEmail(user.getEmail());
        logininfo.setSalt(user.getSalt());
        logininfo.setPassword(user.getPassword());
        logininfoMapper.update(logininfo);
    }

    @Override
    public void del(Long id) {
        User user = userMapper.findOne(id);
        logininfoMapper.del(user.getLogininfoId());
        super.del(id);
    }

    @Override
    public void patchDel(Long[] ids) {
        for (Long id : ids) {
            User user = userMapper.findOne(id);
            logininfoMapper.del(user.getLogininfoId());
            super.del(id);
        }
    }

    @Override
    @Transactional
    public AjaxResult phoneRegister(Map<String, String> map) {
        //获取前端传入的值
        String phone = map.get("phone");
        String phoneCode = map.get("phoneCode");
        String pwd = map.get("pwd");
        String rePwd = map.get("rePwd");
        //空值校验
        if (StrUtil.isBlank(phone)){
            throw new BusinessException("手机号码不能为空！");
        }
        if (StrUtil.isBlank(phoneCode)){
            throw new BusinessException("验证码不能为空！");
        }
        if (StrUtil.isBlank(pwd) || StrUtil.isBlank(rePwd)){
            throw new BusinessException("密码不能为空！");
        }
        //判断验证码是否正确
        Object phoneCodeObj = redisTemplate.opsForValue().get("register:" + phone);
        if (phoneCodeObj == null){
            throw new BusinessException("手机验证码过期！");
        }
        if (!phoneCodeObj.toString().split(":")[0].equals(phoneCode)){
            throw new BusinessException("手机验证码错误！");
        }
        //判断两次密码是否一致
        if (!pwd.equals(rePwd)){
            throw new BusinessException("两次密码不一致！");
        }
        //判断该号码是否注册过 - 在发送短信验证码的时候已经判断过了
        //添加到数据库
        //先添加logininfo
        Logininfo logininfo = addLogininfo(map);
        logininfoMapper.add(logininfo);
        //再添加user
        User user = new User();
        BeanUtils.copyProperties(logininfo,user);
        user.setState(1); // 启用
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
        return new AjaxResult();
    }

    @Override
    @Transactional
    public AjaxResult emailRegister(Map<String, String> map) throws MessagingException {
        //获取前端传入的值
        String email = map.get("email");
        String pwd = map.get("pwd");
        String rePwd = map.get("rePwd");
        //校验
        //校验邮箱格式
        String format = "^[a-z0-9A-Z]+[- |a-z0-9A-Z._]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$";
        if (!Pattern.matches(format, email)){
            throw new BusinessException("邮箱格式不正确！");
        }
        if (StrUtil.isBlank(email)){
            throw new BusinessException("邮箱不能为空！");
        }
        if (StrUtil.isBlank(pwd) || StrUtil.isBlank(rePwd)){
            throw new BusinessException("密码不能为空！");
        }
        //判断两次密码是否一致
        if (!pwd.equals(rePwd)){
            throw new BusinessException("两次密码不一致！");
        }
        //判断该邮箱是否注册过
        User byEmail = userMapper.findByEmail(email);
        if (byEmail != null){
            throw new BusinessException("该邮箱已注册过了！");
        }

        //添加到数据库
        //先添加logininfo
        Logininfo logininfo = addLogininfo(map);
        logininfoMapper.add(logininfo);
        //再添加user
        User user = new User();
        BeanUtils.copyProperties(logininfo,user);
        user.setState(0); // 禁用
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
        //发送激活邮件
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("2097862548@qq.com");
        helper.setSubject("店铺激活邮件");
        //true - 能够再内容中编写html标签 - 会解析
        helper.setText("<h1>账号已注册成功!!!</h1>" +
                "<a href='http://127.0.0.1:8080/user/register/"+ logininfo.getId() +"'>点击该链接激活账号</a>",true);
        //收件人
        helper.setTo(email);
        try {
            javaMailSender.send(mimeMessage);
        } catch (MailException e) {
            throw new BusinessException("该邮箱不存在！");
        }
        return new AjaxResult();
    }

    /** 激活账号 */
    @Override
    public void active(Long id) {
        Logininfo logininfo = logininfoMapper.findOne(id);
        User user = userMapper.findByLogininfoId(id);
        logininfo.setDisable(true);
        user.setState(1);
        logininfoMapper.update(logininfo);
        userMapper.update(user);
    }

    /** 添加logininfo */
    private Logininfo addLogininfo(Map<String, String> map) {
        String phone = map.get("phone");
        String email = map.get("email");
        String pwd = map.get("pwd");
        Logininfo logininfo = new Logininfo();
        //电话为空，就是邮箱注册
        if (phone == null){
            logininfo.setUsername(email);
            //邮箱注册：没激活前是禁用状态
            logininfo.setDisable(false);
        }else if(email == null){
            //邮箱为空，就是手机号注册
            logininfo.setUsername(phone);
            //电话注册，直接启用状态
            logininfo.setDisable(true);
        }
        logininfo.setPhone(phone);
        logininfo.setEmail(email);
        //生成盐值，再加密加盐
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        logininfo.setSalt(salt);
        logininfo.setPassword(md5Pwd);
        logininfo.setType(1); //用户
        return logininfo;
    }
}
